<template>
  <div>
    <el-input placeholder="请输入url" v-model="msg">
      <template slot="prepend">
        <el-select v-model="method" placeholder="选择请求方法" style="width: 120px;">
          <el-option label="GET" value="GET"></el-option>
          <el-option label="POST" value="POST"></el-option>
          <el-option label="PUT" value="PUT"></el-option>
          <el-option label="DELETE" value="DELETE"></el-option>
        </el-select>
      </template>
      <template slot="append">
        <el-button :disabled="!msg" type="primary" @click="sendRequest">Send</el-button>
      </template>
    </el-input>

    <el-tabs type="border-card"> 
      <!-- Param Tab -->
      <el-tab-pane label="Param">
        <el-table :data="params" style="width: 100%">
          <el-table-column prop="key" label="Key">
            <template slot-scope="scope">
              <el-input v-model="scope.row.key"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="value" label="Value">
            <template slot-scope="scope">
              <el-input v-model="scope.row.value"></el-input>
            </template>
          </el-table-column>
          <el-table-column width="80">
            <template slot-scope="scope">
              <el-button @click.native.prevent="deleteRow(scope.$index, params)" type="text" size="small">
                Delete
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button @click="addParam" type="text">Add Param</el-button>
      </el-tab-pane>

      <!-- Body Tab -->
      <el-tab-pane label="Body">
        <el-input type="textarea" v-model="body" :rows="10" placeholder="Enter request body"></el-input>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import axios from 'axios';
export default {
  props: {
    requestData: {
      type: Object,
      default: () => ({
        url: '',
        method: 'GET',
        params: [],
        body: ''
      })
    }
  },
  data() {
    return {
      msg: this.requestData.url,
      method: this.requestData.method,
      params: this.requestData.params,
      body: this.requestData.body,
      response: ''
    };
  },
  watch: {
    // 监听 props 的变化，确保数据更新
    requestData(newValue) {
      this.msg = newValue.url;
      this.method = newValue.method;
      this.params = newValue.params;
      this.body = newValue.body;
    }
  },

  methods: {
    async sendRequest() {
      try {
      const url = this.msg;
      const params = this.params;
      const method = this.method;
      const body = this.body;
      let res;

      // 根据选择的请求方法发送请求
      if (this.method === 'GET') {
        // GET 请求
        res = await axios.get(url, { params: this.params });
      } else if (this.method === 'POST') {
        // POST 请求，传递 body 内容
        res = await axios.post(url, this.body);  // 直接将 body 内容传递给 POST 请求
      }else if(this.method ==='PUT'){
        res = await axios.put(url,this.body)
      }else if(this.method ==='DELETE'){
        res = await axios.delete(url,{params: this.params})
      }

      // 将返回的 JSON 数据直接赋给 response
      this.response = res.data;
      const record = {
        id: new Date().getTime().toString(),
        name: url,
        method,
        url,
        params,
        body,
        date: new Date().toLocaleDateString(),
      }
      this.$store.dispatch('addHistory',record);

      this.$store.dispatch('setResponse', res.data);
      } catch (error) {
        console.error('请求失败:', error);

      // 处理失败时的数据，创建一个包含错误信息的对象
      const errorResponse = {
        message: '请求失败，请检查 URL',
        error: error.message || 'Unknown error', // 额外存储错误消息
      };

      // 将错误数据保存到 Vuex 中
      this.$store.dispatch('setResponse', errorResponse);
   }
},
    addParam() {
      this.params.push({ key: '', value: '' });
    },
    deleteRow(index, arr) {
      arr.splice(index, 1);
    },
  },
};
</script>

<style scoped>
/* 可以在这里添加样式 */
</style>
